﻿using CPPEI.Coolzon.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.Views
{
    public class VersionInfo
    {
        private const string PATH = "Coolzon\\Apps";
        private static VersionInfo _versionInfo;
        public static VersionInfo Instance
        {
            get
            {
                if (_versionInfo == null)
                {
                    _versionInfo = new VersionInfo();
                }
                return _versionInfo;
            }
        }

        private VersionInfo()
        {
        }

        /// <summary>
        /// 根据启动路径从注册表获取版本信息
        /// </summary>
        /// <param name="Version"></param>
        /// <returns></returns>
        public string GetVersion(string startupPath)
        {
            string keyName = GetKeyName(startupPath);

            return  RegistryUtility.ReadString(PATH + "\\" + keyName + "Folder", "version");
        }

        /// <summary>
        /// 根据启动路径获取对应key值，如不存在则创建
        /// </summary>
        /// <param name="startupPath"></param>
        /// <param name="keyName"></param>
        /// <returns></returns>
        private string GetKeyName(string startupPath)
        {
            string keyName = string.Empty;
            Dictionary<string, string> dc = RegistryUtility.GetKeyValueList(PATH);
            if (dc != null && dc.ContainsValue(startupPath))
            {
                keyName = dc.First(a => a.Value.Equals(startupPath)).Key;
            }
            else
            {
                if (dc == null)
                    keyName = "APP1";
                else
                    keyName = "APP" + (dc.Count + 1);

                RegistryUtility.WriteString(PATH, keyName, startupPath);
                RegistryUtility.WriteString(PATH + "\\" + keyName + "Folder", "version", "1.1");
            }

            return keyName;
        }

        /// <summary>
        /// 更新版本信息
        /// </summary>
        /// <param name="startupPath"></param>
        public void UpdateVersion(string startupPath, string version)
        {
            string keyName = GetKeyName(startupPath);

            RegistryUtility.WriteString(PATH + "\\" + keyName + "Folder", "version", version);
        }
    }
}
